<?php
class dblayer {
	public function add_layer($label,$database) {
		$i = $this->dbcount();
		$this->databases[$i] = array('label' =>$label,'config' => $database);
    $this->dbindex[$label] = $i;
	}
	private function dbcount() {
    return count($this->databases);
  }
  public function param($label,$parameter) {
  	 //returns a parameter value of a given database
    if (isset($this->dbindex[$label])) {
		  if (isset($this->databases[$this->dbindex[$label]]['config'][$parameter])) {
		  	if ($parameter != "password") {
		    	return $this->databases[$this->dbindex[$label]]['config'][$parameter];
		    }
		  } else {
		    return false;
		  } 
    } else {
    	return false;
    }
  }
  private function internal_param($label,$parameter) {
  	 //returns a parameter value of a given database
    if (isset($this->dbindex[$label])) {
		  if (isset($this->databases[$this->dbindex[$label]]['config'][$parameter])) {
		    	return $this->databases[$this->dbindex[$label]]['config'][$parameter];
		  } else {
		    return false;
		  } 
    } else {
    	return false;
    }
  }
  public function query($label,$query) {
  	$dbhost = $this->internal_param($label,"dbhost");
  	$dbname = $this->internal_param($label,"dbname");
  	$dbuser = $this->internal_param($label,"dbuser");
  	$dbpass = $this->internal_param($label,"dbpass");
  	$dbtype = $this->internal_param($label,"dbtype");
  	$return = null;
  	switch ($dbtype) {
  	case "mysql":
  	case "mysqli":
  		//create a mysqli query
  		$mysqli = new mysqli($dbhost,$dbuser,$dbpass,$dbname);
  		if ($result = $mysqli->query($query)) {
					if ($mysqli->insert_id > 0) {
						$return = array();
						$return['result'] = $result;
						$return['insert_id'] = $mysqli->insert_id;
					} else {
						$return = $result;
					}
					$mysqli->close();
  		}
  	break;
  	}
  	return $return;
  }
  public function pager_query() {
  
  }
  public function build_query_list($label,$query,$field) {
  	$list = "(";
  	$result = $this->query($label,$query);
  	if ($result->num_rows) {
  		$my_i = 1;
								while ($row = $result->fetch_object()) {
									$evalcode = "\$list .= \$row->$field;";
									eval($evalcode);
									if (($result->num_rows - $my_i) > 0) {
										$list .= ",";
									}
									$my_i++;
								}//while
  	} else {
  		$list .= "0";
  	}
  	$list .= ")";
  	return $list;
  }
private $databases = array();
private $dbindex = array();
}
?>
